<?php 

	include("config.php");
    include(INCLUDEDIR."core.php");
	include("acceso.php");
	
	$tpl = new Plantilla();
	$tpl->setPlantilla("tpl.institutos.html");
	$tpl->prepare();

	$texto = isset($_GET['texto'])?sanitizar($_GET['texto']):"";
	
	if($_GET['idi'] && $_GET['accion']=="eliminar_instituto") {
		$id_instituto = intval($_GET['idi']); 
		$instituto = db::getRow("SELECT * FROM institutos WHERE id_instituto = '$id_instituto'");
		$query = "SELECT count(*) FROM personas WHERE id_instituto = '$id_instituto'";
		$n = intval(db::ExecuteScalar($query));
		if($n>0) {
			redir($_SERVER['PHP_SELF'],"El instituto tiene alumnos asociados (no se pudo eliminar)",true);	
		}		
		mysql_query("DELETE FROM institutos WHERE id_instituto = '$id_instituto'");
		registrar_log("Ha eliminado ".$instituto['nombre_instituto']);
		redir($_SERVER['PHP_SELF'],"El instituto ha sido eliminado.");
	}

	$tpl->newBlock("FORMULARIOINSTITUTO");
	$tpl->assign("texto",$texto);
	Post2Get();
	
	
	
	$query = "SELECT __CAMPOS__ FROM institutos __WHERE__ ";		
			
	$orden = "ORDER BY nombre_instituto ASC ";
			
		
	$filtros = array();
	if(strlen($texto)>1) {
		$filtros[] = db::SearchText($texto,array ("institutos") );
	}
	
	if(count($filtros)>0) {
		$query = str_replace("__WHERE__","WHERE (".implode(" AND ",$filtros).")",$query);	
	} else {
		$query = str_replace("__WHERE__","",$query);	
	}
	
	
	
	// PAGINACION 
	$maxitems = 30;	
	$totalitems =intval(db::ExecuteScalar(str_replace("__CAMPOS__","count(*)",$query)));
	$totalpaginas = ceil($totalitems/$maxitems);
	$pagina_actual = intval($_GET['pa']);
	$offset = $pagina_actual*$maxitems;
	$tpl->assign("paginacion",paginacion($totalpaginas,$pagina_actual,$totalitems));
	// PAGINACION
	
	
	$result = mysql_query(str_replace("__CAMPOS__","*",$query).$orden." LIMIT $maxitems OFFSET $offset");
	if($result && mysql_num_rows($result)>0) {
		$tpl->newBlock("LISTAINSTITUTOS");	
		while($fila = mysql_fetch_assoc($result)) {
			$tpl->newBlock("FILAINSTITUTO");
			foreach($fila as $key => $value) {
				$tpl->assign($key,$value);	
			}
		}
		
	} else {
		$tpl->newBlock("SINRESULTADOS");	
	}
	
	$tpl->Mostrar();
?>